package com.group2.view;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.*;
import model.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.*;

import model.Course;
import model.MyCourseTime;
import com.group2.util.DbUtil;
import javax.swing.GroupLayout.Alignment;
import javax.swing.table.DefaultTableModel;
import static model.netBase.IP;
import javax.swing.LayoutStyle.ComponentPlacement;
/*选课系统模块：
 * 学生查询待选课程
 * 实现选课、退课功能
 * 查看我的课表
 * */
public class CourseMainViewFrame_Student extends javax.swing.JFrame {
	private JTable courseTable;//待选课表
	private JTable courseTableSelected;//已选课程表
	private JScrollPane jScrollPane1;//待选课程表
	private JScrollPane jScrollPane2;//已选课程表
	private JButton jb_confirm;//选课
	private JButton jb_delete;//退课
	private JButton jb_mycoursetable;//显示我的课表
	private JButton jb_search;//按名称搜索
	private JButton jb_return;//返回全部课程
	private JLabel jLabel1;
	private JLabel jLabel2;
	private JTextField s_courseNameTxt;
	private JTextField s_courseTeacherTxt;
	private JPanel jPanel1;
	private JPanel jPanel2;
	private CourseTableFrame MyCourseFrame;
	DbUtil dbUtil = new DbUtil();
	//CourseDao courseDao = new CourseDao();
	//SelectionDao selectionDao = new SelectionDao();
	private Course newCourse;
	private int capacity;
	private int numSelected;
	private String courseId = null;
	private String courseSelectedId=null;
	private String studentId=null;
	private Timer timer;
	boolean f=false;
	boolean g =false;
	private static ArrayList<Course> list = null;//服务端获取的可选课队列本地存档
	private static ArrayList<Course>Courses = new ArrayList<>();//学生选上的课的本地存档
	
	public void checkTimeConflict() {
		System.out.println(list.size());
		for (int i = 0; i < list.size(); i++) {
			for (int i1 = 0; i1 < Courses.size(); i1++) {
				//如果课程日期相同，才考虑冲突，否则不考虑
				MyCourseTime courseTime = list.get(i).getCourseTime();
				MyCourseTime courseTime1 = Courses.get(i1).getCourseTime();
				if (courseTime.getClassWeek() == courseTime1.getClassWeek()) {
					//在同一日期，检测时间是否冲突。一方的结束时间早于另一方的开始时间便不冲突
					if (courseTime.getClassEnd() > courseTime1.getClassEnd() ||
							courseTime1.getClassEnd() > courseTime.getClassEnd()) {
						//不冲突
					} else {
						//冲突
						list.get(i).setCourseTimeConflict(true);
					}
				} else {
					//不在同一日期，一定不冲突
				}
			}

		}
	}
	public CourseMainViewFrame_Student(String id,Timer time) throws IOException, ClassNotFoundException {
		initComponents();
		timer=time;
		studentId =id;
		reFresh();
		Courses.clear();
		reFreshSelected();
		this.fillTable(list);
		time.start();
		this.addMouseMotionListener(new MouseMotionListener() {@Override public void mouseDragged(MouseEvent e) {}@Override public void mouseMoved(MouseEvent e) {time.stop();}});
		this.addMouseListener(new MouseListener() {@Override public void mouseClicked(MouseEvent e) {}@Override public void mousePressed(MouseEvent e) {}@Override public void mouseReleased(MouseEvent e) {}@Override public void mouseEntered(MouseEvent e) {time.start();}@Override public void mouseExited(MouseEvent e) {time.start();}});
		MyCourseFrame = new CourseTableFrame(studentId,time);
		this.setSize(920,685);
	}
	private void reFresh() throws IOException, ClassNotFoundException {
		System.out.println("开始传输");
		//拉取选课队列
		Socket socket = new Socket(IP(), 2000);//此处主机地址请自行修改
		//设置超时时间
		socket.setSoTimeout(3000);
		//构建IO
		OutputStream os = socket.getOutputStream();
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
		bw.write("41" + '\n'+studentId+'\n');
		bw.flush();
		//从服务端输入到本地
		InputStream is = socket.getInputStream();
		ObjectInputStream in = new ObjectInputStream(is);
		Object obj = in.readObject();
		System.out.println("传输结束");
		list = (ArrayList<Course>) obj;
		System.out.println(list.get(0).getCourseName());
		//输出输入流关闭
		is.close();
		os.close();
		socket.close();
	}
	private void reFreshSelected() throws IOException, ClassNotFoundException {
		Courses.clear();
		int size=list.size();
		int index=0;
		while(size>0)
		{
			if(list.get(index).getChoosen()==true)
			{
				Courses.add(list.get(index));
			}
			index++;
			size--;
		}
		this.fillStudentTable(Courses);
		checkTimeConflict();
	}
	private void fillTable(ArrayList<Course> course) {
		
		//在表格中填充coursetime时请首先调用getCourseTime()转化为string类型
		DefaultTableModel dtm = (DefaultTableModel) courseTable.getModel();
		dtm.setRowCount(0);
		try {
			int size = course.size();
			int index = 0;
			while (size > 0) {
				Vector v = new Vector();
				if(course.get(index).getChoosen()) v.add(course.get(index).getCourseId()+" （已选)");
				else if(course.get(index).getCourseTimeConflict()) v.add(course.get(index).getCourseId()+" （冲突)");
				else v.add(course.get(index).getCourseId()) ;v.add(course.get(index).getCourseName());v.add(course.get(index).getCourseTime().toString());v.add(course.get(index).getCourseLocation());v.add(course.get(index).getCourseTeacher());v.add(course.get(index).getCourseCapacity());v.add((course.get(index).getCourseCapacity() - course.get(index).getCourseRemainingCapacity()));
				dtm.addRow(v);
				size--;
				index++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void fillStudentTable(ArrayList<Course> course) {
		//在表格中填充coursetime时请首先调用getCourseTime()转化为string类型
		DefaultTableModel dtm = (DefaultTableModel) courseTableSelected.getModel();
		dtm.setRowCount(0);
		try {
			int size = course.size();
			int index = 0;
			while (size > 0) {
				Vector v = new Vector();v.add(course.get(index).getCourseId());v.add(course.get(index).getCourseName());v.add(course.get(index).getCourseTime().toString());v.add(course.get(index).getCourseLocation());v.add(course.get(index).getCourseTeacher());
				dtm.addRow(v);
				size--;
				index++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void initComponents() {
		
		this.setResizable(false);
		
		jScrollPane1 = new JScrollPane();
		jScrollPane2 = new JScrollPane();
		courseTable = new JTable();
		courseTableSelected = new JTable();
		jPanel1 = new JPanel();
		jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("待选课程"));
		jPanel2 = new JPanel();
		jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("已选课程"));
		
		//setClosable(true);
		//setIconifiable(true);
		setTitle("我的选课系统 - My course system");
		//待选课程
		courseTable.setModel(new javax.swing.table.DefaultTableModel(new Object[][]{

		}, new String[]{"课程编号", "课程名称", "上课时间", "上课地点","任课老师", "课程容量", "已选人数"}) {
			boolean[] canEdit = new boolean[]{false, false, false, true, true,false,false};
			public boolean isCellEditable(int rowIndex, int columnIndex) {
				return canEdit[columnIndex];
			}
		});
		courseTable.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mousePressed(java.awt.event.MouseEvent evt) {
				courseTableMousePressed(evt);
			}
		});
		jScrollPane1.setViewportView(courseTable);
		//已选课程
		courseTableSelected.setModel(new javax.swing.table.DefaultTableModel(new Object[][]{

		}, new String[]{"课程编号", "课程名称", "上课时间", "上课地点", "任课老师"}) {
			boolean[] canEdit = new boolean[]{false, false, false, false, false};

			public boolean isCellEditable(int rowIndex, int columnIndex) {
				return canEdit[columnIndex];
			}
		});
		courseTableSelected.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mousePressed(java.awt.event.MouseEvent evt) {
				courseTableSelectedMousePressed(evt);
			}
		});
		
		s_courseNameTxt=new JTextField();
		s_courseTeacherTxt=new JTextField();
		jLabel1=new JLabel("课程名称");
		jLabel2=new JLabel("上课时间");
		jb_return=new JButton("全部课程");
		jb_return.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt)  {
				try {
					jb_returnActionPerformed(evt);
				} catch (ClassNotFoundException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
		});
		jb_search=new JButton("查询");
		jb_search.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				try {
					jb_searchActionPerformed(evt);
				} catch (IOException e) {
					throw new RuntimeException(e);
				} catch (ClassNotFoundException e) {
					throw new RuntimeException(e);
				}
			}
		});
		
		
		
		jScrollPane2.setViewportView(courseTableSelected);
		jb_delete = new JButton();
		jb_delete.setText("退课");
		jb_delete.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				try {
					jb_deleteActionPerformed(evt);
				} catch (IOException e) {
					throw new RuntimeException(e);
				} catch (ClassNotFoundException e) {
					throw new RuntimeException(e);
				}
			}
		});
		jb_confirm = new JButton();
		jb_confirm.setText("选课");
		jb_confirm.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jb_confirmActionPerformed(evt);
			}
		});
		jb_mycoursetable = new JButton();
		jb_mycoursetable.setText("我的课表");
		jb_mycoursetable.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				try {
					jb_mycoursetableActionPerformed(evt);
				} catch (IOException e) {
					throw new RuntimeException(e);
				} catch (ClassNotFoundException e) {
					throw new RuntimeException(e);
				}
			}
		});
		javax.swing.GroupLayout layout1 = new javax.swing.GroupLayout(jPanel1);
		layout1.setHorizontalGroup(
			layout1.createParallelGroup(Alignment.LEADING)
				.addGroup(layout1.createSequentialGroup()
					.addGroup(layout1.createParallelGroup(Alignment.LEADING)
						.addGroup(layout1.createSequentialGroup()
							.addGap(65)
							.addComponent(jLabel1)
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(s_courseNameTxt, GroupLayout.PREFERRED_SIZE, 158, GroupLayout.PREFERRED_SIZE)
							.addGap(43)
							.addComponent(jLabel2)
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(s_courseTeacherTxt, GroupLayout.PREFERRED_SIZE, 174, GroupLayout.PREFERRED_SIZE)
							.addGap(83)
							.addComponent(jb_search, GroupLayout.PREFERRED_SIZE, 67, GroupLayout.PREFERRED_SIZE)
							.addGap(18)
							.addComponent(jb_return))
						.addGroup(layout1.createSequentialGroup()
							.addContainerGap()
							.addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 795, Short.MAX_VALUE)))
					.addContainerGap())
		);
		layout1.setVerticalGroup(
			layout1.createParallelGroup(Alignment.LEADING)
				.addGroup(layout1.createSequentialGroup()
					.addContainerGap()
					.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 233, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(layout1.createParallelGroup(Alignment.LEADING)
						.addGroup(layout1.createSequentialGroup()
							.addGap(20)
							.addGroup(layout1.createParallelGroup(Alignment.BASELINE)
								.addComponent(jb_search)
								.addComponent(jb_return)))
						.addGroup(layout1.createSequentialGroup()
							.addGap(18)
							.addGroup(layout1.createParallelGroup(Alignment.BASELINE)
								.addComponent(jLabel1)
								.addComponent(s_courseNameTxt, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE)
								.addComponent(jLabel2)
								.addComponent(s_courseTeacherTxt, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE))))
					.addContainerGap(23, Short.MAX_VALUE))
		);
		jPanel1.setLayout(layout1);
		javax.swing.GroupLayout layout2 = new javax.swing.GroupLayout(jPanel2);
		layout2.setHorizontalGroup(
			layout2.createParallelGroup(Alignment.LEADING)
				.addGroup(layout2.createSequentialGroup()
					.addGroup(layout2.createParallelGroup(Alignment.LEADING)
						.addGroup(layout2.createSequentialGroup()
							.addGap(252)
							.addComponent(jb_confirm)
							.addGap(46)
							.addComponent(jb_delete)
							.addGap(34)
							.addComponent(jb_mycoursetable))
						.addGroup(layout2.createSequentialGroup()
							.addContainerGap()
							.addComponent(jScrollPane2, GroupLayout.DEFAULT_SIZE, 795, Short.MAX_VALUE)))
					.addContainerGap())
		);
		layout2.setVerticalGroup(
			layout2.createParallelGroup(Alignment.LEADING)
				.addGroup(layout2.createSequentialGroup()
					.addContainerGap()
					.addComponent(jScrollPane2, GroupLayout.PREFERRED_SIZE, 200, GroupLayout.PREFERRED_SIZE)
					.addGap(18)
					.addGroup(layout2.createParallelGroup(Alignment.BASELINE)
						.addComponent(jb_mycoursetable)
						.addComponent(jb_confirm)
						.addComponent(jb_delete))
					.addContainerGap(39, Short.MAX_VALUE))
		);
		jPanel2.setLayout(layout2);
		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		layout.setHorizontalGroup(
			layout.createParallelGroup(Alignment.LEADING)
				.addGroup(layout.createSequentialGroup()
					.addContainerGap()
					.addGroup(layout.createParallelGroup(Alignment.TRAILING, false)
						.addComponent(jPanel2, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addComponent(jPanel1, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 762, Short.MAX_VALUE))
					.addContainerGap(51, Short.MAX_VALUE))
		);
		layout.setVerticalGroup(
			layout.createParallelGroup(Alignment.LEADING)
				.addGroup(layout.createSequentialGroup()
					.addContainerGap()
					.addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, 321, GroupLayout.PREFERRED_SIZE)
					.addGap(18)
					.addComponent(jPanel2, GroupLayout.PREFERRED_SIZE, 302, GroupLayout.PREFERRED_SIZE)
					.addContainerGap(110, Short.MAX_VALUE))
		);
		getContentPane().setLayout(layout);
		pack();
		this.setLocationRelativeTo(null);
		this.setSize(800,700);
	}

	private void courseTableSelectedMousePressed(MouseEvent evt) {
		int row = courseTableSelected.getSelectedRow();
		courseSelectedId = String.valueOf(((String) courseTableSelected.getValueAt(row, 0)).charAt(0));
		System.out.println(courseSelectedId);
	}

	private void courseTableMousePressed(java.awt.event.MouseEvent evt) {
		int row = courseTable.getSelectedRow();
		courseId = String.valueOf(((String) courseTable.getValueAt(row, 0)).charAt(0));
		capacity =  (int)courseTable.getValueAt(row, 5);//课容量
		numSelected = (int)courseTable.getValueAt(row, 6);//课程数
		 f =list.get(row).getCourseTimeConflict();
		 g=list.get(row).getCourseChooseStation();
		//添加进新Course对象
		newCourse = new Course(list.get(row).getCourseId(),list.get(row).getCourseName(),list.get(row).getCourseTime(),list.get(row).getCourseTeacher(),list.get(row).getCourseLocation(),list.get(row).getCourseCapacity());
	}
	//在待选课表中选课
	private void jb_confirmActionPerformed(java.awt.event.ActionEvent evt) {
		if (courseId == null) {
			JOptionPane.showMessageDialog(this, "请选择一门课程！");
			return;
		}
		if (capacity <= numSelected) {
			JOptionPane.showMessageDialog(this, "该课程已选满,请选择其他课程.");
			return;
		}
		if(f&&!g) {JOptionPane.showMessageDialog(this, "该课程冲突,请选择其他课程.");
			return;}
		int n = JOptionPane.showConfirmDialog(this, "确定要选择该门课程吗?");
		//1.请调用该course的selectCourse()函数修改已选人数
		//2.请将该课程加到该用户类下的已选课程vector中
		if (n == 0) {
			try {
				System.out.println("开始传输");
				//拉取选课队列
				Socket socket = new Socket(IP(), 2000);//此处主机地址请自行修改
				//设置超时时间
				socket.setSoTimeout(3000);
				//构建IO
				OutputStream os = socket.getOutputStream();
				InputStream is = socket.getInputStream();
				BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
				BufferedReader br = new BufferedReader(new InputStreamReader(is));
				//传输请求业务+学生id
				System.out.println(courseId);
				bw.write("43" + '\n'+studentId+'\n'+courseId+'\n');
				bw.flush();
				//从服务端输入到本地
				String str= br.readLine();
				System.out.println(str);
				System.out.println("传输结束");
				//输出输入流关闭
				os.close();
				socket.close();
				//判断是否能够选上课
				if (str.equals("true")) {
					JOptionPane.showMessageDialog(this, "选课成功!");
					//选课成功后重新从服务器处拉取数据
					newCourse.setCourseChooseStation(true);
					Courses.add(newCourse);
					this.fillStudentTable(Courses);
					reFresh();
					checkTimeConflict();
					this.fillTable(list);
				} else {
					JOptionPane.showMessageDialog(this, "已选过该门课程!");
					reFresh();
					checkTimeConflict();
					this.fillTable(list);
				}
			} catch (Exception e) {
				e.printStackTrace();
				JOptionPane.showMessageDialog(this, "已选过该门课程!");
			}
		}
	}
		//在已选课表中退课
		private void jb_deleteActionPerformed (java.awt.event.ActionEvent evt) throws IOException, ClassNotFoundException {
			//1.请调用该course的deleteCourse()函数修改已选人数
			//2.请将该课程从该用户类下的已选课程vector中删除
			if(courseSelectedId==null) {
				JOptionPane.showMessageDialog(this, "请在已选课程列表中选择要退课的课程！");
				return ;
			}
			Socket socket = new Socket(IP(), 2000);//此处主机地址请自行修改
			//设置超时时间
			socket.setSoTimeout(3000);
			//构建IO
			OutputStream os = socket.getOutputStream();
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
			bw.write("47"+'\n'+studentId+'\n'+courseSelectedId+'\n');
			bw.flush();
			//从服务端输入到本地
			System.out.println("开始传输");
			//输出输入流关闭
			InputStream is = new BufferedInputStream(socket.getInputStream());
			BufferedReader br= new BufferedReader(new InputStreamReader(is));
			String str=br.readLine();
			if(str.equals("true")) JOptionPane.showMessageDialog(this, "退课成功");
			else JOptionPane.showMessageDialog(this, "退课失败");
			os.close();
			socket.close();
			System.out.println("传输结束");
			reFresh();
			Courses.clear();
			reFreshSelected();
			checkTimeConflict();
			fillTable(list);
		}
		//显示我的课表
		private void jb_mycoursetableActionPerformed (java.awt.event.ActionEvent evt) throws IOException, ClassNotFoundException {
			MyCourseFrame.setVisible(true);
		}
		//按名称搜索课程
		private void jb_searchActionPerformed (java.awt.event.ActionEvent evt) throws IOException, ClassNotFoundException {
			String s_courseName = this.s_courseNameTxt.getText();
			String s_courseTime=this.s_courseTeacherTxt.getText();
			MyCourseTime c=new MyCourseTime();
			String time =c.toEnglish(s_courseTime);
			Socket socket = new Socket(IP(), 2000);//此处主机地址请自行修改
			//设置超时时间
			socket.setSoTimeout(3000);
			//构建IO
			OutputStream os = socket.getOutputStream();
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
			bw.write("46"+'\n'+s_courseName+'\n'+time+'\n'+studentId+'\n');
			bw.flush();
			//从服务端输入到本地
			System.out.println("开始传输");
			InputStream is = socket.getInputStream();
			ObjectInputStream in = new ObjectInputStream(is);
			Object obj = in.readObject();
			list = (ArrayList<Course>) obj;
			System.out.println(list);
			//输出输入流关闭
			is.close();
			os.close();
			socket.close();
			System.out.println("传输结束");
			checkTimeConflict();
			fillTable(list);

		}
		//返回全部课程
		public void jb_returnActionPerformed (java.awt.event.ActionEvent evt)throws IOException, ClassNotFoundException {

			reFresh();
			checkTimeConflict();
			this.fillTable(list);
		}
		
		
//		public static void main (String args[]){
//			java.awt.EventQueue.invokeLater(new Runnable() {
//				public void run() {
//					try {
//						new CourseMainViewFrame_Student("09020324").setVisible(true);
//					} catch (IOException e) {
//						throw new RuntimeException(e);
//					} catch (ClassNotFoundException e) {
//						throw new RuntimeException(e);
//					}
//				}
//			});
//		}
}


